I wanted to create easily create and link articles (like this one) for this site. In order to do this, I decided to create a static site generator. After some light research, I decided on expanding on one I found online that uses python (see below). It is not perfect, but it gets the job done by using a general template for the articles and a specific template for each hobby.
#!/usr/bin/python3
from markdown2 import markdown
from jinja2 import Environment, FileSystemLoader
from json import load
from datetime import datetime
import os
template_env = Environment(loader=FileSystemLoader(searchpath='./'))
template = template_env.get_template('templates/main.html')
all_articles = []
links = []
tags = set()
article_dir = 'articles/'
articles = os.listdir(article_dir)
for md in articles:
with open(article_dir + md) as markdown_file:
article = markdown(markdown_file.read(),
extras=['fenced-code-blocks', 'code-friendly'])
temp = article.split('\n')[0]
tag = temp[3:len(temp)-4].lower().replace(' ', '_')
_date = datetime.fromtimestamp(os.path.getmtime(article_dir + md)).date()
link = f'<li>{_date} | <a href="hobbies/{tag}/{md[:len(md)-3]}.html">{md[:len(md)-3]}</a></li>'
link_alt = f'<li>{_date} | <a href="{tag}/{md[:len(md)-3]}.html">{md[:len(md)-3]}</a></li>'
all_articles.append([_date, tag, link_alt])
links.append(link)
tags.add(tag)
file_path = f'site/hobbies/{tag}/'
with open(f'{file_path}/{md[:len(md)-3]}.html', 'w', encoding='utf8') as output_file:
output_file.write(
template.render(
title=md[:len(md)-3],
hobby=tag.title().replace('_', ' '),
hobby_link=tag,
date=_date,
content='\n'.join(article.split('\n')[1:])
)
)
all_articles.sort(reverse=True)
links.sort(reverse=True)
template = template_env.get_template('templates/hobbies.html')
str_all_articles = "\n".join(links)
with open('site/hobbies.html', 'w', encoding='utf8') as output_file:
output_file.write(
template.render(
content=f'<ul>{str_all_articles}</ul>'
)
)
for t in tags:
vars()[f'{t}_articles'] = []
for data in all_articles:
exec(f'{data[1]}_articles.append(data[2])')
for t in tags:
exec(f'temp = "\\n".join({t}_articles)')
template = template_env.get_template(f'templates/{t}.html')
with open(f'site/hobbies/{t}.html', 'w', encoding='utf8') as output_file:
output_file.write(
template.render(
content=f'<ul>{temp}</ul>'
)
)